package com.yilei.testninegridview

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView

class ItemDecoration(private val spanCount: Int, private val spacing: Int) : RecyclerView.ItemDecoration() {

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        val position = parent.getChildAdapterPosition(view) // 获取项的位置
        val column = position % spanCount // 获取项的列

        // 顶部间隙（第一行不需要）
        outRect.top = if (position < spanCount) 0 else spacing

        // 底部间隙（最后一行不需要）
        if (position >= (parent.adapter?.itemCount ?: 0) - spanCount) {
            outRect.bottom = 0
        } else {
            outRect.bottom = spacing
        }

        // 左右间隙
        outRect.left = if (column == 0) 0 else spacing // 第一列不设置左边间隙
        outRect.right = if (column == spanCount - 1) 0 else spacing // 最后一列不设置右边间隙
    }
}

